function cmdWinKeyPressedCallback(mode)
% CMDWINKEYPRESSEDCALLBACK Register and unregister a KeyPressedCallback
% function in the MATLAB command window
% 
%   Detailed explanation goes here... soon ;)

% The jCmdWin reference is only a reference to the container of the Command
% Window (including the scrollbars etc.), so setting the callbacks on it
% doesn't work. You need to set it on the actual edittable pane, which is
% xCmdWndView
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jCmdWin = jDesktop.getClient('Command Window');
jCmdWin = jCmdWin.getComponent(0).getComponent(0).getComponent(0); % com.mathworks.mde.cmdwin.XCmdWndView
hCmdWin = handle(jCmdWin,'CallbackProperties');

% Focus command window
jCmdWin.requestFocus;

if ischar(mode) && strcmp(lower(mode), 'enable')
    % Set / register KeyPressedCallback
    set(hCmdWin, 'KeyPressedCallback', @keyPressedCallback);
    % set(hCmdWin, 'KeyPressedCallback', {@keyPressedCallback,hCmdWin});
else
    % Unset / delete KeyPressedCallback
    set(hCmdWin, 'KeyPressedCallback', '');
end%if
end%cmdWinKeyPressedCallback()

function keyPressedCallback(src,evt)
% src = javahandle_withcallbacks.com.mathworks.mde.cmdwin.XCmdWndView
% evt = java.awt.event.KeyEvent


switch get(evt, 'KeyChar')
    case ' '
        localVar = evalin('base', 'isPaused');
        evalStr = sprintf('%s = localVar;', 'isPaused');
        eval(evalStr);
        if isPaused
            %fprintf('\b'); % delete pressed key 's' in the command window
            disp('Resume!');
            evalin('base', 'isPaused = false;');
            
        else
            %fprintf('\b'); % delete pressed key 's' in the command window
            disp('Pause!');
            evalin('base', 'isPaused = true;');
            
        end
        
    case 's'
        %fprintf('\b'); % delete pressed key 's' in the command window
        disp('Stop!');
        evalin('base', 'isStopped = true;');
        
    case 'p'
        %fprintf('\b'); % delete pressed key 'p' in the command window
        disp('Plot!');
        plotResults;
        
    case 't'
        evalin('base', 'stopWatch(end+1) = rem(now,1);');
        fprintf('\nStopped time at: %s\n', datestr(rem(now,1), 'HH:MM:SS.FFF'));
        
end%switch
end%keyPressedCallback()

function plotResults

% Extract the value of the specified variables in the MATLAB base workspace
% and captures their values in the local variables
vars = {'results_tx', 'results_ty', 'results_tz', ...
        'results_e0', 'results_e1', 'results_e2', 'results_e3', ...
        'results_time', 'results_counter', 'nLocators'};
for i = 1:length(vars)
    localVar = evalin('base', vars{i});
    evalStr = sprintf('%s = localVar;', vars{i});
    eval(evalStr);
end

% Einheitsquaternionen in Drehwinkel um Z, Y, X-Achse alpha, beta, gamma
% umrechnen:
for iLoc = 1:nLocators
    for i = 1:length(results_e0{iLoc})
        R = convertUnitQuaternion2RotationMatrix([results_e0{iLoc}(i) results_e1{iLoc}(i) results_e2{iLoc}(i) results_e3{iLoc}(i)]);
        [results_alpha{iLoc}(i), results_beta{iLoc}(i), results_gamma{iLoc}(i) ] = convertRotationMatrix2ZYXEulerAngles(R);
    end
end


% Zeit zwischen 1. und letztem Bild in Sekunden:
time_overall =  results_time(end) - results_time(1);
time_mean = time_overall/length(results_time);
freq_mean = 1/time_mean;
fprintf('overall measurement time: %f sec\n', time_overall);
fprintf('mean time per frame: %f sec\n', time_mean);
fprintf('mean measurement frequency: %f Hz\n', freq_mean);

%% Trajektorien plotten:
if ~exist('fig_traj','var');
    fig_traj = figure(  'Color', 'white', ...
        'Name', 'trajectories');
else
    clf(fig_traj);
end

%% Trajektorien plotten:
if ~exist('fig_traj','var');
    fig_traj = figure(  'Color', 'white', ...
                        'Name', 'trajectories'); 
else
    clf(fig_traj);
end

%%
subplot(2,3,1);
stairs(results_time, results_tx{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('x in mm');
grid on;
hold on; % plotte Standardabweichung
plot( results_time, ones(1,length(results_tx{iLoc}))*(mean(results_tx{iLoc})-sqrt(var(results_tx{iLoc}))), 'color', 'b', 'linewidth', 2  )
plot( results_time, ones(1,length(results_tx{iLoc}))*(mean(results_tx{iLoc})+sqrt(var(results_tx{iLoc}))), 'color', 'b', 'linewidth', 2  )
% plotte Regressionsgerade
b = robustfit(results_time, results_tx{iLoc});
plot(results_time, b(1)+b(2)*results_time, 'k-');


subplot(2,3,2);
stairs(results_time, results_ty{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('y in mm');
grid on;
hold on; % plotte Standardabweichung
plot( results_time, ones(1,length(results_ty{iLoc}))*(mean(results_ty{iLoc})-sqrt(var(results_ty{iLoc}))), 'color', 'b', 'linewidth', 2  )
plot( results_time, ones(1,length(results_ty{iLoc}))*(mean(results_ty{iLoc})+sqrt(var(results_ty{iLoc}))), 'color', 'b', 'linewidth', 2  )
% plotte Regressionsgerade
b = robustfit(results_time, results_ty{iLoc});
plot(results_time, b(1)+b(2)*results_time, 'k-');

subplot(2,3,3);
stairs(results_time, results_tz{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('z in mm');
grid on;
hold on; % plotte Standardabweichung
plot( results_time, ones(1,length(results_tz{iLoc}))*(mean(results_tz{iLoc})-sqrt(var(results_tz{iLoc}))), 'color', 'b', 'linewidth', 2  )
plot( results_time, ones(1,length(results_tz{iLoc}))*(mean(results_tz{iLoc})+sqrt(var(results_tz{iLoc}))), 'color', 'b', 'linewidth', 2  )
% plotte Regressionsgerade
b = robustfit(results_time, results_tz{iLoc});
plot(results_time, b(1)+b(2)*results_time, 'k-');

subplot(2,3,4);
stairs(results_time, results_gamma{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('gamma in rad');
grid on;

subplot(2,3,5);
stairs(results_time, results_beta{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('beta in rad');
grid on;

subplot(2,3,6);
stairs(results_time, results_alpha{iLoc}, 'k.', 'MarkerSize', 1);
xlabel('time in s');
ylabel('alpha in rad');
grid on;

figure;
plot3(results_tx{iLoc}, results_ty{iLoc}, results_tz{iLoc}, 'k.', 'MarkerSize', 1);
grid on;
xlabel('x');
ylabel('y');
zlabel('z');
end%plotResults()